package com.panopset.flywheel;

import java.util.Vector;

/**
 *
 * @author Karl Dinwiddie
 */
class ImpliedQuitFilter {

    Vector<Command> addImpliedQuits(final Vector<Command> commands) {
        Vector<Command> rtn = new Vector<Command>();
        if (commands == null) return rtn;
        Command first = null;
        boolean checkOnce = false;
        for (Command command : commands) {
            if (first == null) {
                first = command;
            }
            if (command instanceof CommandFile) {
                insertImpliedQuitBefore(command);
                command.template.commandFile = (CommandFile) command;
            }
            if (command.next == null && command.template.commandFile != null) {
                if (checkOnce) {
                    throw new RuntimeException("Structure error, report to Panopset, with steps to reproduce.");
                }
                ImpliedQuit iq = new ImpliedQuit(command.template);
                command.next = iq;
                iq.prev = command;
                checkOnce = true;
            }
        }
        Command command = first;
        while (command != null) {
            rtn.add(command);
            command = command.next;
        }
        return rtn;
    }

    private void insertImpliedQuitBefore(Command command) {
        if (command.template.commandFile == null) {
            return;
        }
        ImpliedQuit iq = new ImpliedQuit(command.template);
        iq.next = command;
        if (command.prev != null) {
            iq.prev = command.prev;
            command.prev.next = iq;
        }
    }

}
